package cn.edu.henu.team.ui_login;

import androidx.appcompat.widget.Toolbar;
import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.base.BaseActivity;
import cn.edu.henu.team.bean._User;
import cn.edu.henu.team.constant.ModelConstant;
import cn.edu.henu.team.widget.VerifyCodeButton;
import cn.edu.henu.team.utils.RegexUtils;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputLayout;
import com.mob.MobSDK;
import org.json.JSONException;
import org.json.JSONObject;

public class ForgetPasswordActivity extends BaseActivity {
    EventHandler handler;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_telephone)
    TextInputLayout mPhone;
    @BindView(R.id.et_otpCode)
    TextInputLayout mCode;
    @BindView(R.id.bt_get_code)
    VerifyCodeButton getotpcode;
    @BindView(R.id.PasswordText)
    TextInputLayout mPassword;
    @BindView(R.id.title)
    TextView title;
    private Context mContext;
    private EditText mEdtPhone;
    private EditText mEdtCode;
    private EditText mEdtPassword;
    private String telephone,password,otpCode;
    private final String TAG = "ForgetPasswordActivity";

    @Override
    protected int initLayout() {
        return R.layout.activity_forget_password;
    }

    @Override
    protected void initView() {
        mContext = this;
    }

    @Override
    protected void initData() {
        MobSDK.init(this, ModelConstant.MOB_APPKEY, ModelConstant.MOB_APPSECRET);

        //初始化Toolbar
        toolbar.setTitle("");
        title.setText("忘记密码");
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回消息更新上个Activity数据
                setResult(RESULT_OK, new Intent());
                finish();
            }
        });

        //获取输入的内容
        mEdtPhone = mPhone.getEditText();
        mEdtCode = mCode.getEditText();
        mEdtPassword = mPassword.getEditText();

        //设置监听对输入的数据进行合法性校验
        mEdtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String phone = charSequence.toString();
                if (!RegexUtils.checkPhone(phone)) {
                    mEdtPhone.setError("请输入正确的手机号");
                } else {
                    mCode.setErrorEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        mEdtCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String code = charSequence.toString();
                if (!RegexUtils.checkCode(code)) {
                    mCode.setError("请输入正确的验证码");
                } else {
                    mCode.setErrorEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        mEdtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String password = charSequence.toString();
                if (!RegexUtils.checkPassword(password)) {
                    mPassword.setError("请输入正确的密码");
                } else {
                    mPassword.setErrorEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });

        handler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                _User user = BmobUser.getCurrentUser(_User.class);
                                user.setPassword(password);
                                user.update(user.getObjectId(), new UpdateListener() {
                                    @Override
                                    public void done(BmobException e) {
                                        if (e==null){
                                            showToastInThread(mContext,"密码修改成功");
                                            startActivity(new Intent(ForgetPasswordActivity.this,LoginActivity.class));
                                        }
                                    }
                                });
                            }
                        });
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ForgetPasswordActivity.this, "验证码已发送", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    }
                } else {
                    ((Throwable) data).printStackTrace();
                    Throwable throwable = (Throwable) data;
                    try {
                        JSONObject obj = new JSONObject(throwable.getMessage());
                        final String des = obj.optString("detail");
                        if (!TextUtils.isEmpty(des)) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ForgetPasswordActivity.this, "提交错误信息", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        };
        SMSSDK.registerEventHandler(handler);
    }

    /*
     * 监听事件
     */
    @OnClick({R.id.bt_get_code, R.id.btn_finish})
    public void onClick(View view) {

        telephone = mEdtPhone.getText().toString();
        password = mEdtPassword.getText().toString();
        otpCode = mEdtCode.getText().toString();

        switch (view.getId()) {
            case R.id.bt_get_code: // 获取验证码
                if (TextUtils.isEmpty(telephone)) {
                    Toast.makeText(ForgetPasswordActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    if (RegexUtils.checkPhone(telephone)) {
                        SMSSDK.getVerificationCode("86", telephone);
                    } else {
                        Toast.makeText(ForgetPasswordActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.btn_finish:   // 完成
                forgetPasswordFinish();
                break;
        }
    }

    private void forgetPasswordFinish() {
        if (telephone.length() == 0) {
            Toast.makeText(mContext, "请输入注册手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (otpCode.length() == 0) {
            Toast.makeText(mContext, "请输入验证码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (password.length() == 0) {
            Toast.makeText(mContext, "请输入新密码", Toast.LENGTH_SHORT).show();
            return;
        }
        SMSSDK.submitVerificationCode("86", telephone, otpCode);
    }
}